package com.fs.orm.auth;

import com.fasterxml.jackson.annotation.JsonIgnore;

import com.fs.orm.entity.SysUser;
import jdk.nashorn.internal.objects.annotations.Getter;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.util.CollectionUtils;

import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

public class LoginUser implements UserDetails {

	private static final long serialVersionUID = -3685249101751401211L;

	// 登录IP
	private String ipAddr;

	private Set<SysRole> sysRoles;

	private Set<String> permissions;

	private String username;

	private String password;

	public String getIpAddr() {
		return ipAddr;
	}

	public void setIpAddr(String ipAddr) {
		this.ipAddr = ipAddr;
	}

	public Set<SysRole> getSysRoles() {
		return sysRoles;
	}

	public void setSysRoles(Set<SysRole> sysRoles) {
		this.sysRoles = sysRoles;
	}

	public Set<String> getPermissions() {
		return permissions;
	}

	public void setPermissions(Set<String> permissions) {
		this.permissions = permissions;
	}

	@Override
	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	@Override
	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	/***
	 * 权限重写,返回分配给用户的角色列表
	 */
	@JsonIgnore
	@Override
	public Collection<? extends GrantedAuthority> getAuthorities() {
		Collection<GrantedAuthority> collection = new HashSet<>();
		if (!CollectionUtils.isEmpty(sysRoles)) {
			sysRoles.parallelStream().forEach(role -> {
				if (role.getCode().startsWith("ROLE_")) {
					collection.add(new SimpleGrantedAuthority(role.getCode()));
				} else {
					collection.add(new SimpleGrantedAuthority("ROLE_" + role.getCode()));
				}
			});
		}

		if (!CollectionUtils.isEmpty(permissions)) {
			permissions.parallelStream().forEach(per -> {
				collection.add(new SimpleGrantedAuthority(per));
			});
		}

		return collection;
	}

	//账户是否未过期
	@Override
	public boolean isAccountNonExpired() {
		return true;
	}

	//账户是否未锁定
	@Override
	public boolean isAccountNonLocked() {
		return true;
	}

	//密码是否未过期
	@Override
	public boolean isCredentialsNonExpired() {
		return true;
	}

	//账户是否激活	
	@Override
	public boolean isEnabled() {
		return true;
	}

}
